package Xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;

import Authorization.User;
import Levels.LevelWrapper;
import Path.ProjectPath;
import Session.TestSession;
import Source.QuestionsWrapper;
import com.google.common.collect.Lists;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Igor
 * Date: 24.11.13
 * Time: 19:34
 * To change this template use File | Settings | File Templates.
 */
public class DOMUserSessionParser {
    String userLogin;
    int[] levelArray;
    int pausedLevel;
    int savedPoints;
    String[] savedAnswersArray;
    Document document;
    String filePath = new ProjectPath().getProjectPath()+"\\src\\main\\java\\Xml\\UserSessions.xml";
    XPath xpath;
    String query;
    XPathExpression expr;
    Object result;
    NodeList nodeList;

    /**
     * Метод заполняет поля класса которые соответствуют полям userSession по логину юзера.
     * @param userName
     * @throws XPathExpressionException
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    private void createUserSessionParameters(String userName) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
        userLogin = userName;
        loadDocument();
        XPathFactory factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
        readLevelArrayFromFile();
        readPausedLevelFromFile();
        readSavedPointsFromFile();
        readSavedAnswersArrayFromFile();
    }

    private void loadDocument() throws ParserConfigurationException, IOException, SAXException {
        File xmlFile = new File(filePath);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.parse(xmlFile);
        document.getDocumentElement().normalize();
    }

    private void readLevelArrayFromFile() throws XPathExpressionException {
        query = "//userSession[login=" + "'" + userLogin + "'" + "]/levelArray/text()";
        expr = xpath.compile(query);
        result = expr.evaluate(document, XPathConstants.NODESET);
        nodeList = (NodeList)result;
        String stringLevelArray;
        try {
            stringLevelArray = nodeList.item(0).getNodeValue();
            levelArray = getIntArray(stringLevelArray);
        } catch (NullPointerException npe){

        }


    }

    private void readPausedLevelFromFile() throws XPathExpressionException {
        query = "//userSession[login=" + "'" + userLogin + "'" + "]/pausedLevel/text()";
        expr = xpath.compile(query);
        result = expr.evaluate(document, XPathConstants.NODESET);
        nodeList = (NodeList)result;
        try {
            pausedLevel = Integer.parseInt(nodeList.item(0).getNodeValue());
        } catch (NullPointerException nullPointerEx){
            pausedLevel = 0;
        }

    }

    private void readSavedPointsFromFile() throws XPathExpressionException {
        query = "//userSession[login=" + "'" + userLogin + "'" + "]/savedPoints/text()";
        expr = xpath.compile(query);
        result = expr.evaluate(document, XPathConstants.NODESET);
        nodeList = (NodeList)result;
        try {
            savedPoints = Integer.parseInt(nodeList.item(0).getNodeValue());
        }
         catch (NullPointerException npex){
             savedPoints=0;
         }
    }

    private void readSavedAnswersArrayFromFile() throws XPathExpressionException {
        query = "//userSession[login=" + "'" + userLogin + "'" + "]/savedAnswers/text()";
        expr = xpath.compile(query);
        result = expr.evaluate(document, XPathConstants.NODESET);
        nodeList = (NodeList)result;
        try {
            savedAnswersArray = nodeList.item(0).getNodeValue().split(",");
        } catch (NullPointerException npex){
            savedAnswersArray = null;
        }

    }

    private int[] getIntArray(String string) {
        String[] stringArray = string.split(",");
        int[] intArray = new int[stringArray.length];
        for (int i = 0; i < stringArray.length;  i++) {
            intArray[i] = Integer.parseInt(stringArray[i]);
        }
        return intArray;
    }

    public TestSession getLoadedSession(User user, QuestionsWrapper wrapper){

        try {
           createUserSessionParameters(user.getLogin());
        } catch (XPathExpressionException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ParserConfigurationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if(savedAnswersArray!=null){
            LevelWrapper loadedLevel = new LevelWrapper(levelArray);

         return new TestSession(wrapper,loadedLevel,pausedLevel,savedPoints,savedAnswersArray);
        }
        else {
            return new TestSession(wrapper);
        }
    }

    public int getPoints(User simpleUser) {
        try {
           createUserSessionParameters(simpleUser.getLogin());
        } catch (XPathExpressionException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SAXException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ParserConfigurationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return savedPoints;

    }



}
